<?php
/**
 * 订单
 *
 * @copyright  Copyright (c) 2015-2025 NcPHP Inc. (http://www.ncphp.com)
 * @license    http://www.ncphp.com/
 * @link       http://www.ncphp.com/
 * @author     NcPHP Team
 * @since      File available since Release v1.1
 */
defined('InNcPHP') or exit('Access Invalid!');

class orderControl extends BaseHomeControl{

    public function __construct(){
        $this->update_order_status();
        parent::__construct();
    }

    /**
     * @var ticketModel
     */
    private $ticket_model;

    /**
     * @var ticket_skuModel|ticket_sku_dateModel
     */
    private $sku_model;

    /**
     * @var ticket_dateModel
     */
    private $date_model;

    /**
     * 门票下订单,返回支付参数
     */
    public function placeOp()
    {
        if (chksubmit()) {
            $this->ticket_model = Model('ticket');
            //门票ID
            $tk_id = intval($_POST['tid']);
            /* @var specModel $spec_model */
            $spec_model = Model('spec');
            //票型ID
            $spec_id = intval($_POST['sid']);
            $spec_info = $spec_model->getSpecInfo(array('spec_id'=>$spec_id,'goods_id'=>$tk_id,'type'=>TICKET_MARK));
            //获取门票信息
            $ticket = $this->ticket_model->getTicketInfo(array('tk_id'=>$tk_id));
            if (!$ticket || !$spec_info) {
                $this->showError(4000, '门票不存在');
            } elseif ($_POST['price_type'] == 2) {
                $this->sku_model = Model('ticket_sku');
                /** 正式环境修改表前缀 为pw_**/
                $sku_table = 'nc_ticket_sku';
            } elseif ($_POST['price_type'] == 1) {
                $this->sku_model = Model('ticket_sku_date');
                /** 正式环境修改表前缀 为pw_**/
                $sku_table = 'nc_ticket_sku_date';
                if (!empty($_POST['date'])) {
                    $this->date_model = Model('ticket_date');
                    $date = $this->date_model->getTicketDateInfo(array('tk_id'=>$tk_id,'date'=>trim($_POST['date'])));
                    if (!$date) {
                        $this->showError(4000, '错误的日期');
                    }
                } else {
                    $this->showError(4000, '没有选中的日期');
                }
            } else {
                $this->showError(4000, '错误的门票类型');
            }
            if(empty($_SESSION['member']['member_id']) || $_SESSION['member']['mobile']=='default_id' || empty($_SESSION['member']['mobile'])){
                redirect('index.php?act=login&op=index');exit;
            }
            //当前时间戳
            $time = time();
            //订单表的信息
            $sn =  date('y').str_pad(date('z'), 3, '0', STR_PAD_LEFT).str_pad($_SESSION['member']['member_id'], 8, '0',STR_PAD_LEFT).date('His').mt_rand(100, 999);
            $order_params = array(
                'order_sn' => $sn,
                'ticket_code' => '',
                'member_id' => $_SESSION['member']['member_id'],
                'merchant_id' => $ticket['merchant_id'],
                'ticket_id' => $ticket['tk_id'],
                'ticket_title' => '('.$ticket['tk_title'].')'.$spec_info['spec_name'],
                'ticket_thumb' => $spec_info['surface_img'],
                'tk_show_price' => $ticket['tk_show_price'],
                'tk_full_addr' => $ticket['tk_full_addr'],
                'member_name' => trim($_POST['name']),
                'member_phone' => trim($_POST['phone']),
                'member_idcard' => trim($_POST['idcard']),
                'allow_date' => isset($_POST['date']) ? $_POST['date'] : '',
                'order_status' => 10,
                'add_time' => $time,
                'order_type'=>TICKET_MARK,
                'spec_id'=>$spec_id,
                'spec_name'=>$spec_info['spec_name'],
                'is_set_time'=>$_POST['price_type']==1?1:0,
            );

            //查询用户信息表,如果是新增的则加入
            /* @var member_infoModel $member_info_model */
            $member_info_model = Model('member_info');
            if (!$member_info_model->getMemberInfo(array(
                'member_id'=>$_SESSION['member']['member_id'],
                'mb_name'=>$order_params['member_name'],
                'mb_phone'=>$order_params['member_phone'],
            ))) {
                $member_info_model->addMemberInfo(array(
                    'member_id'=>$_SESSION['member']['member_id'],
                    'mb_name'=>$order_params['member_name'],
                    'mb_phone'=>$order_params['member_phone'],
                    'mb_idcard'=>$order_params['member_idcard'],
                ));
            }

            //判断提交的SKU会否为空
            if (!is_array($_POST['sku'])) {
                $this->showError(4000, '没有门票信息');
            }
            //订单总价
            $totalAmount = 0;
            //订单里面门票总数
            $numAll = 0;
            //订单里的门票
            $order_ticket = array();
            foreach ($_POST['sku'] as $sku_id => $num) {
                $num = intval($num);
                if ($num > 0) {
                    $condition = isset($date) ? array('sku_id'=>$sku_id, 'date_id'=>$date['date_id']) : array('sku_id'=>$sku_id, 'tk_id'=>$tk_id);
                    $sku = $this->sku_model->getTicketSku($condition);
                    //var_dump($sku);exit;
                    if ($num <= intval($sku['sku_store'])) {
                        //订单里的门票
                        $order_ticket[] = array(
                            'sku_id' => $sku_id,
                            'type_name' => $sku['type_name'],
                            'type_id' => $sku['type_id'],
                            'ot_num' => $num,
                            'ot_price' => $sku['sku_price'],
                            'ot_time' => $time,
                        );
                        //计算总价
                        $totalAmount += floatval($sku['sku_price']) * $num;
                        //计算总数
                        $numAll +=$num;
                    } else {
                        $this->showError(4001, $sku['type_name'] . '库存不足');
                    }
                }
            }
            //判断总价和门票类型是否为空
            if ($totalAmount == 0 || empty($order_ticket)) {
                $this->showError(4000, '没有门票信息');
            } else {
                $order_params['need_pay'] = $totalAmount;
            }
            /* @var orderModel $order_model */
            $order_model = Model('order');
            /* @var order_ticketModel $order_ticket_model */
            $order_ticket_model = Model('order_ticket');
            //开始数据库操作
            Model::beginTransaction();
            try {
                $order_id = $order_model->addOrder($order_params);
                if ($order_id) {
                    foreach ($order_ticket as $t) {
                        $sql = "update ".$sku_table." set sku_store=sku_store-".$t['ot_num'].",sku_time=".$time." where sku_id=".$t['sku_id']." and sku_store >= ".$t['ot_num'];
                        $res_update = Model()->execute($sql);
                        if ($res_update) {
                            unset($t['sku_id']);
                            unset($t['type_name']);
                            $t['order_id'] = $order_id;
                            $res = $order_ticket_model->addOrderTicket($t);
                            if (!$res) {
                                throw new Exception('订单保存失败', 4002);
                            }
                        } else {
                            throw new Exception($t['type_name'].'库存不足', 4001);
                        }
                    }
                    Model::commit();
                    $this->ticket_model->addTicketSales($tk_id);//销量加一
                    $spec_model->addSpecSales($spec_id,$numAll);//增加销量
                    //此处是要发起支付的参数
                    $pay = $this->pay($order_params['order_sn'],$_GET['t']);
                    exit(json_encode(array('errcode'=>0,'errmsg'=>$pay)));
                } else {
                    throw new Exception('订单保存失败', 4002);
                }
            } catch (\Exception $e) {
                $this->showError($e->getCode(), $e->getMessage());
                Model::rollback();
            }
        }
    }

    /**
     * 酒店下单,返回支付参数
     */
    public function hotel_placeOp()
    {
        if(chksubmit()){
            /* @var hotelModel $hotel_model */
            $hotel_model = Model('hotel');
            /* @var specModel $spec_model */
            $spec_model = Model('spec');
            /* @var order_hotelModel $order_hotel_model */
            $order_hotel_model = Model('order_hotel');
            $hotel_id = intval($_POST['hotel_id']);//酒店ID
            $spec_id  = intval($_POST['spec_id']);//房型或底下的服务ID
            $num = $_POST['num']; //客户所预定的房间数量
            $day = $_SESSION['hotel_time']['numdate'];//客户所入驻的夜数
            //获取信息
            $hotel_info = $hotel_model->getHotelInfo(array('id'=>$hotel_id,'ht_status'=>1),'hotel_name,id,merchant_id,hotel_name,ht_full_addr');
            $spec_info  = $spec_model->getSpecInfo(array('spec_id'=>$spec_id,'is_show'=>1));
            if($spec_info['goods_id']!=$hotel_info['id']){
                $this->showError(4000, '酒店信息和房型信息不匹配');
            }
            if(empty($_SESSION['member']['member_id']) || $_SESSION['member']['mobile']=='default_id'){
                redirect('index.php?act=login&op=index');exit;
            }
            //查询房型库存的公共必须条件
            $_where =array();
            $_where['startdate'] = array('elt',$_SESSION['hotel_time']['enddate']);
            $_where['enddate'] = array('gt',$_SESSION['hotel_time']['startdate']);
            $_where['status'] = 1;
            //判断是否属于房型底下的套餐信息
            if($spec_info['parent_id']>0){
                //获取房型信息
                $spec_info_1  = $spec_model->getSpecInfo(array('spec_id'=>$spec_info['parent_id'],'is_show'=>1));
                if(empty($spec_info_1)){
                    $this->showError(4000, '非法操作');
                }
                //获取库存
                $_where['spec_id'] = $spec_info_1['spec_id'];
                $hotel_oh_num = $order_hotel_model->getOrderHoteloh_num($_where);
                if($num>($spec_info_1['stock']-$hotel_oh_num['sum_on_num'])){
                    $this->showError(4000, '房间数量不足');
                }
                //$all_price = floatval($spec_info_1['price']*$num*$day);
            }else{

                 //获取库存
                $_where['spec_id'] = $spec_info['spec_id'];
                $hotel_oh_num = $order_hotel_model->getOrderHoteloh_num($_where);

                if($num>($spec_info['stock']-$hotel_oh_num['sum_on_num'])){
                    $this->showError(4000, '房间数量不足');
                }

            }
            $all_price = floatval($spec_info['price']*$num*$day);
            //生成订单前准备
            //订单表的信息
            $sn =  date('y').str_pad(date('z'), 3, '0', STR_PAD_LEFT).str_pad($_SESSION['member']['member_id'], 8, '0',STR_PAD_LEFT).date('His').mt_rand(100, 999);
            $order_params = array(
                'order_sn'=>$sn,
                'ticket_code'=>'',
                'member_id'=>$_SESSION['member']['member_id'],
                'merchant_id'=>$hotel_info['merchant_id'],
                'ticket_id'=>$hotel_id,//此处为商品ID
                'ticket_title'=>$hotel_info['hotel_name'],//酒店名称
                'tk_show_price'=>$all_price,
                'ticket_thumb' =>$spec_info['parent_id']>0?$spec_info_1['surface_img']:$spec_info['surface_img'],  //封面图
                'need_pay'=>$all_price,
                'member_name'=>trim($_POST['name']), //收货人
                'member_phone'=>trim($_POST['phone']),
                'add_time'=>time(),
                'order_status'=>10,
                'order_type'=>HOTEL_MARK,  //订单类型
                'spec_name'=>$spec_info['parent_id']>0?$spec_info_1['spec_name'].'('.$spec_info['spec_name'].')':$spec_info['spec_name'],
                'spec_id'=>$spec_info['parent_id']>0?$spec_info_1['spec_id']:$spec_info['spec_id'],
                'tk_full_addr'=>$hotel_info['ht_full_addr'],
            );
            //查询用户信息表,如果是新增的则加入
            /* @var member_infoModel $member_info_model */
            $member_info_model = Model('member_info');
            if (!$member_info_model->getMemberInfo(array(
                'member_id'=>$_SESSION['member']['member_id'],
                'mb_name'=>$order_params['member_name'],
                'mb_phone'=>$order_params['member_phone'],
            ))) {
                $member_info_model->addMemberInfo(array(
                    'member_id'=>$_SESSION['member']['member_id'],
                    'mb_name'=>$order_params['member_name'],
                    'mb_phone'=>$order_params['member_phone'],
                   // 'mb_idcard'=>$order_params['member_idcard'],
                ));
            }
            //开始数据库操作
            /*  @var orderModel $order_model  */
            $order_model = Model('order');
            /*  @var order_hotelModel $order_hotel_model */
            $order_hotel_model = Model('order_hotel');
            Model::beginTransaction();
            try{
                $order_id = $order_model->addOrder($order_params);
                if($order_id>0){
                   //插入酒店的订单信息表中
                    $add_hotel_info = array(
                        'order_id'=>$order_id,
                        'spec_id'=>$spec_info['parent_id']>0?$spec_info['parent_id']:$spec_info['spec_id'],
                        'oh_num'=>$num,
                        'oh_price'=>$all_price,
                        'startdate'=>$_SESSION['hotel_time']['startdate'],
                        'enddate' =>$_SESSION['hotel_time']['enddate'],
                        'numdate' =>$_SESSION['hotel_time']['numdate'],
                        'add_time'=>time(),
                        'status'=>1,
                        'subclass_id'=>$spec_info['parent_id']>0?$spec_info['spec_id']:0,
                        'unit_price'=>$spec_info['price']
                    );
                    $res = $order_hotel_model->addOrderHotel($add_hotel_info);
                    $spec_model->addSpecSales($spec_info['parent_id']>0?$spec_info['parent_id']:$spec_id,$num);//增加规格销量
                    if(!$res){
                        throw new Exception('订单保存失败', 4002);
                    }
                    Model::commit();
                    //此处是要发起支付的参数
                    $pay = $this->pay($order_params['order_sn'],$_GET['t']);
                    exit(json_encode(array('errcode'=>0,'errmsg'=>$pay)));
                }else{
                    throw new Exception('订单保存失败', 4002);
                }
            }catch (\Exception $e){
                $this->showError($e->getCode(), $e->getMessage());
                Model::rollback();
            }
        }
    }

    /**
     * 美食下单，返回支付参数
     */
    public function food_placeOp()
    {
        if(chksubmit()){
            /* @var foodModel $food_model*/
            $food_model = Model('food');
            $fd_id = intval($_POST['fd_id']);
            $num = intval($_POST['num']);
            $spec_id = intval($_POST['spec_id']);
            $info = $food_model->getFoodInfo(array('fd_id'=>$fd_id,'fd_status'=>1));
            if($info['fd_id'] !=$fd_id){
                $this->showError(4000, '商品不存在');
            }
            if(!empty($spec_id)){
                $spec_model = Model('spec');
                $spec_info = $spec_model->getSpecInfo(array('spec_id'=>$spec_id));
                if(empty($spec_info)){
                    $this->showError(4000, '商品规格不存在');
                }
                if($spec_info['is_show']==0){
                    $this->showError(4000, '商品规格已下架');
                }
                if($num>$spec_info['stock']){
                    $this->showError(4000, '商品库存不足');
                }
                $info['price'] = $spec_info['price'];
            }else{
                if($num>$info['stock']){
                    $this->showError(4000, '商品库存不足');
                }
            }
            if(empty($_SESSION['member']['member_id']) || $_SESSION['member']['mobile']=='default_id'){
                redirect('index.php?act=login&op=index');exit;
            }
            $all_price = floatval($info['price']*$num);
            //获取商家信息
            $merchant_model = Model('member_merchant');
            $merchant_adds= $merchant_model->getMerchantInfo(array('merchant_id'=>$info['merchant_id']),'address');
            //生成订单前准备
            //订单表的信息
            $sn =  date('y').str_pad(date('z'), 3, '0', STR_PAD_LEFT).str_pad($_SESSION['member']['member_id'], 8, '0',STR_PAD_LEFT).date('His').mt_rand(100, 999);
            $order_params = array(
                'order_sn'=>$sn,
                'ticket_code'=>'',
                'member_id'=>$_SESSION['member']['member_id'],
                'merchant_id'=>$info['merchant_id'],
                'ticket_id'=>$info['fd_id'],//此处为商品ID
                'ticket_title'=>$info['fd_title'],//美食名称
                'tk_show_price'=>$all_price,
                'ticket_thumb'=>$info['fd_thumb'],
                'need_pay'=>$all_price,
                'member_name'=>trim($_POST['name']), //收货人
                'member_phone'=>trim($_POST['phone']),
                'add_time'=>time(),
                'order_status'=>10,
                'order_type'=>FOOD_MARK,  //订单类型
//                'spec_name'=>$info['fd_title'],
//                'spec_id'=>$info['fd_id'],
                'spec_name'=>empty($spec_info['spec_name'])?$info['fd_title']:$spec_info['spec_name'] ,
                'spec_id'=>empty($spec_info['spec_id'])?0:$spec_id,
                'tk_full_addr'=>$merchant_adds['address'],
                'is_voucher'=>$info['fd_type']>0?1:0,
            );
            //查询用户信息表,如果是新增的则加入
            /* @var member_infoModel $member_info_model */
            $member_info_model = Model('member_info');
            if (!$member_info_model->getMemberInfo(array(
                'member_id'=>$_SESSION['member']['member_id'],
                'mb_name'=>$order_params['member_name'],
                'mb_phone'=>$order_params['member_phone'],
            ))) {
                $member_info_model->addMemberInfo(array(
                    'member_id'=>$_SESSION['member']['member_id'],
                    'mb_name'=>$order_params['member_name'],
                    'mb_phone'=>$order_params['member_phone'],
                    // 'mb_idcard'=>$order_params['member_idcard'],
                ));
            }

            //开始数据库操作
            /*  @var orderModel $order_model  */
            $order_model = Model('order');
            /*  @var order_goodsModel $order_goods_model */
            $order_goods_model = Model('order_goods');
            Model::beginTransaction();
            try{
                $order_id = $order_model->addOrder($order_params);
                $food_model->reduceFoodStock($fd_id,$num);
                if($order_id>0){
                    //插入美食的订单信息表中
                    $add_goods_info = array(
                        'order_id'=>$order_id,
                        'goods_id'=>$info['fd_id'],
                        'og_num'=>$num,
                        'og_price'=>$info['price'],
                        'og_time'=>time(),
                        'deduction'=>$info['fd_type']==1?$info['deduction']:0.00,
                    );
                    $res = $order_goods_model->addOrderGoods($add_goods_info);
                    if(!$res){
                        throw new Exception('订单保存失败', 4002);
                    }
                    Model::commit();
                    $food_model->addFoodSales($fd_id,$num);
                    //此处是要发起支付的参数
                    $pay = $this->pay($order_params['order_sn'],$_GET['t']);
                    exit(json_encode(array('errcode'=>0,'errmsg'=>$pay)));
                }else{
                    throw new Exception('订单保存失败', 4002);
                }
            }catch (\Exception $e){
                $this->showError($e->getCode(), $e->getMessage());
                Model::rollback();
            }
        }
    }

    /**
     * 旅行社下单
     */
    public function itinerary_placeOp()
    {
        if(chksubmit()){
            /* @var itineraryModel $itinerary_model*/
            $itinerary_model = Model('itinerary');
            $ir_id = intval($_POST['ir_id']);
            $num = intval($_POST['num']);
            $itinerary_info = $itinerary_model->getItineraryInfo(array('id'=>$ir_id,'ir_status'=>1));
            if($itinerary_info['id']!=$ir_id){
                $this->showError(4000, '商品不存在');
            }
            if($num>$itinerary_info['stock']){
                $this->showError(4000, '商品库存不足');
            }
            if(empty($_SESSION['member']['member_id']) || $_SESSION['member']['mobile']=='default_id'){
                redirect('index.php?act=login&op=index');exit;
            }
            $all_price = floatval($itinerary_info['price']*$num);
            //生成订单前准备
            //订单表的信息
            $sn =  date('y').str_pad(date('z'), 3, '0', STR_PAD_LEFT).str_pad($_SESSION['member']['member_id'], 8, '0',STR_PAD_LEFT).date('His').mt_rand(100, 999);
            $order_params = array(
                'order_sn'=>$sn,
                'ticket_code'=>'',
                'member_id'=>$_SESSION['member']['member_id'],
                'merchant_id'=>$itinerary_info['merchant_id'],
                'ticket_id'=>$itinerary_info['id'],//此处为商品ID
                'ticket_title'=>$itinerary_info['ir_title'],//美食名称
                'tk_show_price'=>$all_price,
                'ticket_thumb'=>$itinerary_info['ir_thumb'],
                'need_pay'=>$all_price,
                'member_name'=>trim($_POST['name']), //收货人
                'member_phone'=>trim($_POST['phone']),
                'add_time'=>time(),
                'order_status'=>10,
                'order_type'=>ITINERARY_MARK,  //订单类型
                'spec_name'=>$itinerary_info['ir_title'],
                'spec_id'=>$itinerary_info['id'],
                'tk_full_addr'=>$itinerary_info['ir_full_addr'],
            );
            //查询用户信息表,如果是新增的则加入
            /* @var member_infoModel $member_info_model */
            $member_info_model = Model('member_info');
            if (!$member_info_model->getMemberInfo(array(
                'member_id'=>$_SESSION['member']['member_id'],
                'mb_name'=>$order_params['member_name'],
                'mb_phone'=>$order_params['member_phone'],
            ))) {
                $member_info_model->addMemberInfo(array(
                    'member_id'=>$_SESSION['member']['member_id'],
                    'mb_name'=>$order_params['member_name'],
                    'mb_phone'=>$order_params['member_phone'],
                    // 'mb_idcard'=>$order_params['member_idcard'],
                ));
            }

            //开始数据库操作
            /*  @var orderModel $order_model  */
            $order_model = Model('order');
            /*  @var order_goodsModel $order_goods_model */
            $order_goods_model = Model('order_goods');
            Model::beginTransaction();
            try{
                $order_id = $order_model->addOrder($order_params);
                $itinerary_model->reduceItineraryStock($ir_id,$num);
                if($order_id>0){
                    //插入旅行社的订单信息表中
                    $add_goods_info = array(
                        'order_id'=>$order_id,
                        'goods_id'=>$ir_id,
                        'og_num'=>$num,
                        'og_price'=>$itinerary_info['price'],
                        'og_time'=>time(),
                        'startdate'=>$_POST['startdate'],
                        //'deduction'=>$info['fd_type']==1?$info['deduction']:0.00,
                    );
                    $res = $order_goods_model->addOrderGoods($add_goods_info);
                    if(!$res){
                        throw new Exception('订单保存失败', 4002);
                    }
                    Model::commit();
                    $itinerary_model->addItinerarySales($ir_id,$num);
                    //此处是要发起支付的参数
                    $pay = $this->pay($order_params['order_sn'],$_GET['t']);
                    exit(json_encode(array('errcode'=>0,'errmsg'=>$pay)));
                }else{
                    throw new Exception('订单保存失败', 4002);
                }
            }catch (\Exception $e){
                $this->showError($e->getCode(), $e->getMessage());
                Model::rollback();
            }
        }
    }

    /**
     * 获取js支付参数
     * @param string $order_sn
     * @param string $apptype 为空为公众号支付，wx为微信app支付，ali为支付宝app支付
     * @return bool|string
     */
    public function pay($order_sn, $apptype = null)
    {

        /** @var orderModel $order_model */
        $order_model = Model('order');
        $order = $order_model->getOrderInfo(array('order_sn'=>$order_sn, 'order_status'=>10));
        if (empty($order)) {
            //订单不存在
            return false;
        }

        if (empty($apptype)) {
            //公众号支付
            try {
                require_once(BASE_DATA_PATH.'/vendors/weixin/lib/WxPay.Api.php');
                require_once(BASE_DATA_PATH.'/vendors/weixin/util/WxPay.JsApiPay.php');

                $openid = $_SESSION['member']['openid'];

                $input = new WxPayUnifiedOrder();
                $input->SetBody($order['ticket_title']);
                $input->SetOut_trade_no($order_sn);
                $input->SetAttach($order_sn);
                $input->SetTotal_fee(intval($order['need_pay'] * 100));
                $input->SetTime_start(date("YmdHis"));
                $input->SetTime_expire(date("YmdHis", time() + 600));
                $notify_url = HOST_URL."/control/wx_notify.php";
                $input->SetNotify_url($notify_url);
                $input->SetTrade_type("JSAPI");
                $input->SetOpenid($openid);
                $order_data = WxPayApi::unifiedOrder($input);

                $tools = new JsApiPay();
                $jsApiParameters = $tools->GetJsApiParameters($order_data);
                return json_decode($jsApiParameters);
            } catch (\Exception $e) {
                return false;
            }
        } elseif ($apptype == 'wx') {
            //微信app支付
            try{
                return $this->wxpay_app($order['ticket_title'],$order_sn,intval($order['need_pay'] * 100));
            } catch(\Exception $e){

                return false;
            }
      } elseif ($apptype == 'ali') {
            //支付宝app支付
            try {
                return $this->alipay_app($order['ticket_title'], $order_sn, $order['need_pay']);
            } catch (\Exception $e) {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 在订单列表支付
     */
    public function payOp()
    {
        /** @var orderModel $order_model */
        $order_model = Model('order');

        $order_sn = $_POST['order_sn'];
        $orderInfo = $order_model->getOrderInfo(array('order_sn'=>$order_sn, 'order_status'=>10, 'member_id'=>$_SESSION['member']['member_id']));
        if ($orderInfo) {
            $pay = $this->pay($orderInfo['order_sn'], $_GET['t']);
            exit(json_encode(array('errcode'=>0,'errmsg'=>$pay)));
        } else {
            $this->showError(4000, '没有找到订单');
        }
    }

    /**
     * 生成支付宝app支付参数
     * @param string $title
     * @param string $order_sn
     * @param float $amount
     * @return string
     */
    public function alipay_app($title, $order_sn, $amount)
    {
        //sksk
        require_once BASE_DATA_PATH.'/vendors/alipay/AopClient.php';
        $aop = new AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2018011101773187';
        $aop->rsaPrivateKey = 'MIIEowIBAAKCAQEAm1P3EZY8AjvdMs0ltJSObEJQIX6EJDxKydOiOeJAodnHqhHtkWAUNeL7YW0klo7ZVJnEdEdxjzjOWpjQHJNgxYLpOCAwTyqOkzmWjWJpLebl2cOQc9mi9DLSMSDb0A4berU+HG7sAcPDUKXWriTbFlnfKtY7pJv0fmyFQiNkJmVEm3Jfuwk9S43MOtHG/e4upw1I2vpZZTg+xEN2NW5vMtug+jHMim4h34/qQno9a+xF0rKJFpYpBa/iF0Au/vyTBgkaD3M1W8niguUlje0QHCbQGvSghoH6htMXTN88aY8Mo2BRGNrFw64r6C+w7kv/pKARIkd3JChJNSolG/tNQwIDAQABAoIBAA326ouGOjbpMuXSU8V8ZaGOBK4+NZscYIzsnfUeRjlG3xCHNBiRzr9ZfMgxi8yNYzSb7nGVyrvZm5PBkVRAW77mGhmVq0IyzUanMsXbRyF9VMTTNDV2J5RUzVjlX13BJu9NRBxCTK2L8A9cGYTmg1vrEIlFYW9XJhAHqaNckzBwXnNKb0NmFugajTZT80JkeROjDYdBWO/BIcBCWUKnEhEtMtsF0G78ZEwsA0cAk5Hqji3BLIqahSPKsLUQm60iKLcMtUIfJV4vRyqDcV54hPSX/gFSDwJhLk/Nnz4kyVDscmTByMaSZI65Sx8AlzTkT8LQ5fqpHWApmRDJOwSvJgECgYEAyRv7NUFEDHJiPx5zpwgz5K7X92V2mEfV0lVtSdmmwlbnWm+gCcWgyx/tJKb6TpngFY0fTMRPD1NpJvyoWR7tTPGsztFG6myw+yZpY0AiUbTgEygvWTlYVL6FnEq/UT32fY1eBzW0TOYlpdW00YpA03jn+aA/nkF9gVUUc55KzwMCgYEAxbkggUsiayXslIu4QWaIQlFcBhsELjXMuH6lytDnRk82UPWZFXXdAvR0vXtaoQadeh8FUbU1NeytxQVVPWGhh1+5yECWrWr8Kzy9SOluIs79oZsAWr9WdOc9tORni668CvMRhBfYplnj3BZ9YjGp/icr+oDafDJ7zYHJwOAjFMECgYEAvtwsY5VGNJ3Vudt3nRz+ythYpDUKAWmjdtOWPdEvHx8Ev+JSOxPxDvWExRUnVrNYZHujKeLguUXK9LIyPypHwY9XFoysxcxThnck64mxSGPliKjJjt8KgpqyCOszeLHanbstcqA4Ngbx0dnomjigX1JOray008eJidWp7DRdAOsCgYAE+l45Ix0guXm1W7ct3lj74nSAqtl2GGCpHHcsHgpUmNXzP9u00JzZ4DG4O4zSlQoN8w39OqS2UNknJrU4sGaSs/RHeGjSwOjMZeEWHtppAfEcynw9zKdulgvVrBJ3T9ToKap9OuR3e7fi6KYLfNicz3up+OiHS/YV/HiJ5Jq9gQKBgH170er5Fg83GlbVK432cU1egBKwPshtrf9bR1miRFSqgj9AThf2B1e5WqvXOXqrHEONv2HeaFDY/0Vt5LT6BaGg1zFu5o0jYalSQoUw9HM+Gb6Einf5+yhV9xoHA6uR2IVbw8vo0SGKuXq9W6ppNNc5xH03abw/KOOx93l7qRLC';//请填写开发者私钥去头去尾去回车，一行字符串
        $aop->format = 'json';
        $aop->charset = 'UTF-8';
        $aop->signType = 'RSA2';
        $aop->alipayrsaPublicKey   = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAitkV3HWbV9DUqDRPncMnwc0J4zFehoaWzeMtD2ktpMXO/EqcETgmL62hAdKzfFBDuRQ4pOovlFCXPV5PBRwLdcJL3XXdDnem1cPt4dfbAlpfhi+Q31Fkkv97rV56SRIkbBVIRx4PMVr8+Xbk0KPzF+TlxJrCFgxok2fwO7d2izdefH2BR0UMJ7q8r3cllMe7LwTy6tFwa0LnUap0liBRLTBGuU5lNIQTtnjxjjOkfHJ9GpjnHsmbecFADsFPj2sruDr+lT86QBqVfiAs6KBiTYgV+zyW95uBSWD14+jhG7OAZQvEiPsri4ZXiAViSDBRg/KR2DAdOvCu8Ek0mINFLQIDAQAB';//请填写支付宝公钥，一行字符串
        $request = new AlipayTradeAppPayRequest();
        $bizcontent = json_encode(array(
            'subject'=>$title,
            'out_trade_no'=>$order_sn,
            'timeout_express'=>'30m',
            'total_amount'=>sprintf('%.2f',$amount),
            'product_code'=>'QUICK_MSECURITY_PAY',
        ), JSON_UNESCAPED_UNICODE);
        $request->setNotifyUrl(ALI_NOTIFY_URl);
        $request->setBizContent($bizcontent);
        $response = $aop->sdkExecute($request);

        return $response;
    }

    /**
     * 生成微信app支付参数
     * @param string $title
     * @param string $order_sn
     * @param float $amount
     */

    public function wxpay_app($title, $order_sn,$amount){

        require_once BASE_DATA_PATH.'/vendors/weixin/WxPayPubHelper/WxPayHelper.php';
        $WxPayHelper = new WxPayHelper();
        $response = $WxPayHelper->getPrePayOrder($title,$order_sn,$amount);

        $x = $WxPayHelper->getOrder($response['prepay_id']);
        return $x;



    }
    /**
     * 抛出json错误信息
     * @param integer $errcode
     * 4000：错误的提交
     * 4001：库存不足
     * 4002：订单保存失败
     * @param string $errmsg
     */
    private function showError($errcode, $errmsg)
    {
        exit(json_encode(array('errcode'=>$errcode, 'errmsg'=>$errmsg)));
    }


    /**
     * 取消订单
     */
    public function cancelOp()
    {
        /* @var orderModel $order_model */
        $order_model = Model('order');
        /* @var order_ticketModel $order_ticket_model */
        $order_ticket_model = Model('order_ticket');

        $order_sn = $_POST['ordersn'];
        $order = $order_model->getOrderInfo(array('order_sn'=>$order_sn));
        if ($order && $order['order_status'] == 10 && $order['order_type']==2) {
            //还原门票库存
            Model::beginTransaction();
            try {
                $order_tickets = $order_ticket_model->getOrderTicketList(array('order_id'=>$order['order_id']));
                //还原库存
                if ($order['is_set_time']==0) {
                    /** @var ticket_skuModel $sku_model */
                    $sku_model = Model('ticket_sku');
                    foreach ($order_tickets as $ticket) {
                        $condition = array('tk_id'=>$order['ticket_id'],'type_id'=>$ticket['type_id']);
                        $sku_model->table('ticket_sku')->where($condition)->setInc('sku_store', $ticket['ot_num']);
                    }
                } else {
                    /** @var ticket_dateModel $date_model */
                    $date_model = Model('ticket_date');
                    /** @var ticket_sku_dateModel $sku_model */
                    $sku_model = Model('ticket_sku_date');
                    $date = $date_model->getTicketDateInfo(array('tk_id'=>$order['ticket_id'],'date'=>$order['allow_date']));
                    foreach ($order_tickets as $ticket) {
                        $condition = array('date_id'=>$date['date_id'],'type_id'=>$ticket['type_id']);
                        $sku_model->table('ticket_sku_date')->where($condition)->setInc('sku_store', $ticket['ot_num']);
                    }
                }
                $res = $order_model->updateOrder(array('order_id'=>$order['order_id']), array('order_status'=>30));
                if ($res) {
                    Model::commit();
                    $ret = array('errcode'=>0,'errmsg'=>'');
                } else {
                    Model::rollback();
                    $ret = array('errcode'=>0,'errmsg'=>'更新状态失败');
                }
            } catch (\Exception $e) {
                Model::rollback();
                $ret = array('errcode'=>4001,'errmsg'=>$e->getMessage());
            }
        } else if($order && $order['order_status'] == 10 && $order['order_type']==1){
            $order_hotel_model = Model('order_hotel');
            //还原酒店房间
            Model::beginTransaction();
            try{
                $res = $order_model->updateOrder(array('order_id'=>$order['order_id']),array('order_status'=>30));
                $_res=$order_hotel_model->updateOrderHotel(array('order_id'=>$order['order_id']),array('status'=>2));
                if($res&&$_res){
                    Model::commit();
                    $ret = array('errcode'=>0,'errmsg'=>'');
                }else{
                    Model::rollback();
                    $ret = array('errcode'=>0,'errmsg'=>'更新状态失败');
                }
            }catch (\Exception $e) {
                Model::rollback();
                $ret = array('errcode'=>4001,'errmsg'=>$e->getMessage());
            }

        }else if($order && $order['order_status'] == 10 && $order['order_type']==3){
            //还原美食库存或者旅行社库存
            $order_goods = Model('order_goods');
            $res = $order_model->updateOrder(array('order_id'=>$order['order_id']),array('order_status'=>30));
            $good_info = $order_goods->getOrderGoodsInfo(array('order_id'=>$order['order_id']),'og_num,goods_id');
            //释放美食库存
            $food_model = Model('food');
            try{
                $_res = $food_model->addFoodStock($good_info['goods_id'],$good_info['og_num']);
                if($_res && $res){
                    Model::commit();
                    $ret = array('errcode'=>0,'errmsg'=>'');
                }else{
                    Model::rollback();
                    $ret = array('errcode'=>0,'errmsg'=>'更新状态失败');
                }
            } catch(\Exception $e){
                Model::rollback();
                $ret = array('errcode'=>4001,'errmsg'=>$e->getMessage());
            }

            //$ret = array('errcode'=>4000,'errmsg'=>'未找到订单');
        }elseif($order && $order['order_status'] == 10 && $order['order_type']==4){
            //还原美食库存或者旅行社库存
            $order_goods = Model('order_goods');
            $res = $order_model->updateOrder(array('order_id'=>$order['order_id']),array('order_status'=>30));
            $good_info = $order_goods->getOrderGoodsInfo(array('order_id'=>$order['order_id']),'og_num,goods_id');
            //释放美食库存
            $itinerary_model = Model('itinerary');
            try{
                $_res =  $itinerary_model->addItineraryStock($good_info['goods_id'],$good_info['og_num']);
                if($_res && $res){
                    Model::commit();
                    $ret = array('errcode'=>0,'errmsg'=>'');
                }else{
                    Model::rollback();
                    $ret = array('errcode'=>0,'errmsg'=>'更新状态失败');
                }
            } catch(\Exception $e){
                Model::rollback();
                $ret = array('errcode'=>4001,'errmsg'=>$e->getMessage());
            }
        }else{
            $ret = array('errcode'=>4000,'errmsg'=>'未找到订单');
        }
        exit(json_encode($ret));
    }

    /**
     * 发表评论
     */
    public function add_commentOp()
    {
        $order_sn = $_GET['order_sn'];
        /* @var orderModel $order_model */
        $order_model = Model('order');
        $order_info = $order_model->getOrderInfo(array('order_sn'=>$order_sn,'if_comment'=>0,'order_status'=>21));
        if(empty($order_info)){
            showMessage('非法操作');
        }
        if(chksubmit()){
            /* @var commentModel $comment_model */
            $comment_model = Model('comment');
            $order_id = intval($_POST['order_id']);
            $img = $_POST['imgs'];
            $order_info = $order_model->getOrderInfo(array('order_id'=>$order_id,'if_comment'=>0,'order_status'=>21));
            if(empty($order_info)){
                //$this->showError(4000, '非法操作');
                showMessage('非法操作');
            }
            $comment_arr = array();
            if($img!=''){
                if(stripos($img[0],"data:image")!==false){
                    $upload = new UploadFile();
                    $upload->set('default_dir','comment/'.$upload->getSysSetPath());
                    $result = $upload->test_upfile_base64($img[0]);
                    if($result){
                        $comment_arr['pic_1'] = $upload->getBase64_url();
                    }else{
                        //$this->showError(4000, '图片上传失败');
                        showMessage('图片上传失败');
                    }
                }
                if(stripos($img[1],"data:image")!==false){
                    $upload = new UploadFile();
                    $upload->set('default_dir','comment/'.$upload->getSysSetPath());
                    $result = $upload->test_upfile_base64($img[1]);
                    if($result){
                        $comment_arr['pic_2'] = $upload->getBase64_url();
                    }else{
                        //$this->showError(4000, '图片上传失败');
                        showMessage('图片上传失败');
                    }
                }
                if(stripos($img[2],"data:image")!==false) {
                    $upload = new UploadFile();
                    $upload->set('default_dir','comment/'.$upload->getSysSetPath());
                    $result = $upload->test_upfile_base64($img[2]);
                    if($result){
                        $comment_arr['pic_3'] = $upload->getBase64_url();
                    }else{
                       // $this->showError(4000, '图片上传失败');
                        showMessage('图片上传失败');
                    }
                }
            }
            if($order_info['order_type']==1){
                //查询用户的入驻时间
               $startdate =  Model('order_hotel')->getOrderHotelInfo(array('order_id'=>$order_info['order_id']),'startdate');
            }
            $comment_arr['goods_id'] = $order_info['ticket_id'];
            $comment_arr['order_id'] = $order_info['order_id'];
            $comment_arr['member_id'] = $_SESSION['member']['member_id'];
            $comment_arr['member_name'] = $_SESSION['member']['nickname'];
            $comment_arr['serve_point'] =$_POST['serve_point'];//服务评分
            $comment_arr['place_point'] =$_POST['place_point'];//位置评分
            $comment_arr['facility_point'] = $_POST['facility_point'];//设施评分
            $comment_arr['all_point'] = $_POST['all_pint'];//总体评分
            $comment_arr['content'] = $_POST['content'];//文字评价
            $comment_arr['addtime'] = time();
            $comment_arr['cmt_type'] = $order_info['order_type'];
            $comment_arr['merchant_id'] = $order_info['merchant_id'];
            $comment_arr['in_time'] = $order_info['order_type']==1?$startdate['startdate']:'';
            $comment_arr['member_head'] = $_SESSION['member']['headimgurl'];//用户头像
            if($comment_model->addComment($comment_arr)){
                if(Model('order')->updateOrder(array('order_id'=>$order_info['order_id']),array('if_comment'=>1))){
                    showMessage('评价成功','index.php?act=member&op=order&state=3');
                }else{
                    showMessage('评价失败');
                }
            }else{
                showMessage('评价失败');
            }
        }
        Tpl::output('_title','评价订单');
        Tpl::output('order_info',$order_info);
        Tpl::showpage('add.comment','new_layout');
    }



    /**
     * 申请退款
     */
    public function refundOp()
    {
        $order_sn = $_GET['order_sn'];
        /* @var orderModel $order_model */
        $order_model = Model('order');
        /* @var order_ticketModel $order_ticket_model */
        $order_ticket_model = Model('order_ticket');
        $order_info = $order_model->getOrderInfo(array('order_sn'=>$order_sn,'order_status'=>20));
        if(empty($order_info)){
            showMessage('非法操作');
        }
        if(chksubmit()){
            /* @var order_refundModel $refund_model */
            $refund_model = Model('order_refund');
            $order_id = intval($_POST['order_id']);
            $img = $_POST['imgs'];
            $order_info = $order_model->getOrderInfo(array('order_id'=>$order_id,'order_status'=>20));
            if(empty($order_info)){
                showMessage('非法操作');
            }
            //查询该用户是否已经申请过退款了
            $refund = $refund_model->getOrderRefundInfo(array('order_sn'=>$order_info['order_sn']));
            if($refund && is_array($refund)){
                showMessage('请勿重复提交');
            }
            $refund_arr = array();
            if($img!=''){
                if(stripos($img[0],"data:image")!==false){
                    $upload = new UploadFile();
                    $upload->set('default_dir','comment/'.$upload->getSysSetPath());
                    $result = $upload->test_upfile_base64($img[0]);
                    if($result){
                        $refund_arr['pic_1'] = $upload->getBase64_url();
                    }else{
                        //$this->showError(4000, '图片上传失败');
                        showMessage('图片上传失败');
                    }
                }
                if(stripos($img[1],"data:image")!==false){
                    $upload = new UploadFile();
                    $upload->set('default_dir','comment/'.$upload->getSysSetPath());
                    $result = $upload->test_upfile_base64($img[1]);
                    if($result){
                        $refund_arr['pic_2'] = $upload->getBase64_url();
                    }else{
                        //$this->showError(4000, '图片上传失败');
                        showMessage('图片上传失败');
                    }
                }
                if(stripos($img[2],"data:image")!==false) {
                    $upload = new UploadFile();
                    $upload->set('default_dir','comment/'.$upload->getSysSetPath());
                    $result = $upload->test_upfile_base64($img[2]);
                    if($result){
                        $refund_arr['pic_3'] = $upload->getBase64_url();
                    }else{
                        // $this->showError(4000, '图片上传失败');
                        showMessage('图片上传失败');
                    }
                }
            }
            $refund_sn = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $refund_arr['order_id'] = $order_info['order_id'];
            $refund_arr['refund_money'] = $order_info['need_pay'];
            $refund_arr['note'] = $_POST['note'];
            $refund_arr['pay_type'] = $order_info['pay_type'];
            $refund_arr['addtimes'] = time();
            $refund_arr['merchant_id'] = $order_info['merchant_id'];
            $refund_arr['member_id'] = $_SESSION['member']['member_id'];
            $refund_arr['member_phone'] = $_SESSION['member']['mobile'];
            $refund_arr['order_sn'] = $order_info['order_sn'];
            $refund_arr['refund_type'] = $_POST['refund_type'];
            $refund_arr['pay_sn'] = $order_info['pay_sn'];
            $refund_arr['out_refund_no'] = $refund_sn;
            if($refund_model->addOrderRefund($refund_arr)){
                //释放库存
                $this->restore_store($order_info['order_id']);
                if($order_model->updateOrder(array('order_id'=>$order_info['order_id'],'order_status'=>20),array('order_status'=>31,'if_refund'=>1))){
                    //var_dump($order_info['order_id']);exit;
                    showMessage('退款申请提交成功','index.php?act=member&op=order');
                }
            }
         exit;
        }
        switch($order_info['order_type']){
            case 1:
                $order_info['ticket_thumb'] = getGoodsImg($order_info['ticket_thumb'],HOTEL_MARK);
                $skus = Model('order_hotel')->getOrderHotelList(array('order_id'=>$order_info['order_id']));
                break;
            case 2:
                $order_info['ticket_thumb'] = getGoodsImg($order_info['ticket_thumb'],TICKET_MARK);
                $skus = $order_ticket_model->getOrderTicketList(array('order_id'=>$order_info['order_id']));
                break;
            case 3:
                $order_info['ticket_thumb'] = getGoodsImg($order_info['ticket_thumb'],FOOD_MARK);
                $skus = Model('order_goods')->getOrderGoodsList(array('order_id'=>$order_info['order_id']));
                break;
            case 4:
                $order_info['ticket_thumb'] = getGoodsImg($order_info['ticket_thumb'],ITINERARY_MARK);
                $skus = Model('order_goods')->getOrderGoodsList(array('order_id'=>$order_info['order_id']));
                break;
        }
        Tpl::output('order_info',$order_info);
        Tpl::output('skus',$skus);
        Tpl::output('_title','申请退款');
        Tpl::showpage('refund.from','new_layout');
    }


}
